package multimedia;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Displayable;

import midlet.VadeMecumMIDlet;

public class HTTPConnectionThread implements Runnable {

	private VadeMecumMIDlet midlet;

	private Alert alert;

	private Displayable previous;

	private String query;

	public HTTPConnectionThread(VadeMecumMIDlet midlet, Displayable previous, String query) {
		this.query = query;
		this.midlet = midlet;
		this.previous = previous;
		alert = new Alert("", null, null, AlertType.INFO);
	}

	public void run() {
		System.out.println("query on joseki");
		HttpConnection conn = null;
		InputStream is = null;

		try {
			conn = (HttpConnection) Connector.open("http://buchada.dsc.ufcg.edu.br/vademecum2/sparql?query=" + query);

			conn.setRequestMethod(HttpConnection.GET);

			conn.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
			conn.setRequestProperty("Connection", "close");
			
			System.out.println(query);
			
//			String formData = "PREFIX+vade:+<http://www.lsi.dsc.ufcg.edu.br/vademecum.owl%23>%0D%0APREFIX+dc:++++++<http://purl.org/dc/elements/1.1/>%0D%0APREFIX+rdfs:%09+++<http://www.w3.org/2000/01/rdf-schema%23>%0D%0APREFIX+rdf:++++++<http://www.w3.org/1999/02/22-rdf-syntax-ns%23>%0D%0ASELECT+%3Fb%0D%0AWHERE+%0D%0A++{+%0D%0A++++vade:Hugo+vade:hasContext+%3Fc+.%0D%0A++++%3Fc+rdf:type+vade:Emotion+.%0D%0A++++%3Fc+vade:emotionValue+%3Fb%0D%0A++}";//this.query;
//			byte[] data = formData.getBytes();
//			conn.setRequestProperty("Content-Length", Integer.toString(data.length));
//			OutputStream os = conn.openOutputStream();
//			os.write(data);
//			os.close();
			
			int status = conn.getResponseCode();			
			
			if (status != HttpConnection.HTTP_OK) {
				throw new IOException("HTTP Response Code = " + status);
			}

			is = conn.openInputStream();
			int len = (int) conn.getLength();
			System.out.println("LEN = " + len);
			
			if (len > 0) {
				byte[] data2 = new byte[len];
				is.read(data2);
				String retorno = new String(data2);

				System.out.println(retorno);
				alert.setString(retorno);
			} else {
				alert.setString("Empty response :(");
			}
			alert.setTimeout(2000);
			midlet.display.setCurrent(alert, previous);

		} catch(Exception rse) {
			this.midlet.error(rse);
			rse.printStackTrace();
		} finally {
			try {

				if (is != null) {
					is.close();
				}

				if (conn != null) {
					conn.close();
				}

			} catch(Exception e) {
				this.midlet.error(e);
			}

		}

	}
}
